import { toRaw } from "vue"
import { addRouterTabs } from "./routerUtil"
import ignore from "@/config/ignore"

// 路由守卫

/**
 * 路由变化时，根据路由控制menu的key
 *
 * @param {*} to
 * @param {*} from
 * @param {*} next
 */
function routerGuard(store, to, from ,next){
  const loginIgnore = ignore
  if(!store.getters['user/isLogin'] && !loginIgnore.includes(to.path)){
    next({path:'/login'})                                                          
  }else{
    store.dispatch('menu/getMenuItem', {
      fullPath: to.fullPath
    }).then((route) => {
      const routeData = toRaw(route)
      if (routeData) {
        store.commit('menu/setOpenKeys', routeData['openKeys'])
        store.commit('menu/setSelectedKeys', [routeData['fullPath']])
      }
      next()
    });
  }
}

/**
 * 路由变化时，根据路由控制 tabs
 *
 * @param {*} store
 * @param {*} to
 * @param {*} from
 * @param {*} next
 */
function tabsGuard(store, to, from, next){
  // console.log(to, from)
  addRouterTabs(to.fullPath, to.name)
  
  next()
}

export default {
  beforeEach: [routerGuard, tabsGuard]
}